package socket2;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Server {
    private ServerSocket serverSocket;

    private Map<String,PrintWriter> Outlls=new HashMap<>();
    public Server(){
        try {
            System.out.println("正在启动服务器");
            serverSocket=new ServerSocket(8088);
            System.out.println("服务器启动成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void start(){
        try {
            while (true) {
                System.out.println("等待客户端连接...");
                Socket socket = serverSocket.accept();
                System.out.println("客户端连接成功");

                //调用线程并且使用
                Runnable runnable=new ClientHandler(socket);
                Thread t=new Thread(runnable);
                t.start();

            }


        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        Server server=new Server();
        server.start();
    }
    //
    public class ClientHandler implements Runnable{
        private Socket socket;
        private String nickName;
        public ClientHandler(Socket socket){
            this.socket=socket;
        }
        public void run(){
            try {

                //输入流，接收客户端发送来的消息
                InputStream is = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);

                nickName=br.readLine();

                //输出流，用于转发客户端的消息
                OutputStream os= socket.getOutputStream();
                OutputStreamWriter osw=new OutputStreamWriter(os,StandardCharsets.UTF_8);
                BufferedWriter bw=new BufferedWriter(osw);
                PrintWriter pw=new PrintWriter(bw,true);
                //记录该客户端的输出流
                Outlls.put(nickName,pw);
                //进行广播消息，上线通知
                sendMessage(nickName+"上线了"+"当前在线人数："+Outlls.size());


                String message;
                while ((message = br.readLine()) != null) {

                    //判断消息是否是私聊消息
                    if (message.startsWith("@")){
                        sendMessageToOuter(message);
                    }else {
                        sendMessage(nickName+"群发说："+message);
                    }

                }
            } catch (IOException e) {
                //此处客户端断开，不需要处理
            } finally {
                Outlls.remove(nickName);
                //给其他所有在线用户广播下线消息
                sendMessage(nickName+"下线了"+"当前在线人数："+Outlls.size());
                try {
                    socket.close();

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        public void sendMessage(String message){
            System.out.println(message);
            for (PrintWriter pw:Outlls.values()){
                pw.println(message);
            }
        }
        public void sendMessageToOuter(String message){
            //判断是否是私聊消息
            if (!message.matches("@.+:.+")){
                PrintWriter pw=Outlls.get(nickName);
                pw.println("私聊格式错误");
                return;
                //System.out.println("私聊格式错误");
            }

            String tonickName=message.substring(1,message.indexOf(":"));
            if (!Outlls.containsKey(tonickName)){
                PrintWriter pw=Outlls.get(nickName);
                pw.println("该用户不在线");
                return;
            }
            PrintWriter pw=Outlls.get(tonickName);
            String toMessage=message.substring(message.indexOf(":")+1);
            pw.println(nickName+"悄悄对你说:"+toMessage);

        }


    }
}
